package net.greyar.single;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import net.greyar.gear.Machine;
import net.greyar.model.User;

public class Register {
	private static final Random random = new Random(System.currentTimeMillis());
	private static final String PATTERN_ID_USER = "00000.00.0000";
	private static final String PATTERN_ID_MACHINE = "0000.000.00";
	private static Map<String, User> users = Collections.synchronizedMap(new HashMap<String, User>());
	private static Map<String, Machine> machines = Collections.synchronizedMap(new HashMap<String, Machine>());
	
	public static String name(User user) {
		synchronized (users) {
			String name = null;
			while (name == null) {
				 name = newId(PATTERN_ID_USER);
				 if (users.get(name) == null) {
					users.put(name, user);
				 } else {
					 name = null;
				 }
			}
			return name;
		}
	}

	public static String name(Machine machine) {
		synchronized (machines) {
			String name = null;
			while (name == null) {
				 name = newId(PATTERN_ID_MACHINE);
				 if (machines.get(name) == null) {
					 machines.put(name, machine);
				 } else {
					 name = null;
				 }
			}
			return name;
		}
	}

	public static User user(String user) {
		return users.get(user);
	}

	public static Machine machine(String machine) {
		return machines.get(machine);
	}
	
	private static String newId(String pattern) {
		Random r = new Random(System.currentTimeMillis() + random.nextLong());
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < pattern.length(); i++) {
			sb.append(pattern.charAt(i) == '.' ? '.' : String.valueOf(r.nextInt(10)));
		}
		return sb.toString();
	}
}
